<template>
  <div class="chat-container">
    <header class="chat-header">
      <div class="logo-container">
        <div class="logo-gradient">AuroraAI</div>
        <span class="beta-badge">BETA</span>
      </div>
      <div class="status-indicator" :class="statusClass">{{ statusMessage }}</div>
    </header>

    <div class="debug-panel" v-if="showDebug">
      <div class="debug-item">
        <span class="debug-label">最后响应时间：</span>
        <span class="debug-value">{{ lastResponseTime }}ms</span>
      </div>
      <div class="debug-item">
        <span class="debug-label">当前状态：</span>
        <span class="debug-value">{{ statusMessage }}</span>
      </div>
      <div class="debug-item error-message" v-if="error">
        <i class="icon-error"></i>
        {{ error }}
      </div>
    </div>

    <div class="messages" ref="messagesContainer">
      <div v-for="(msg, index) in messages" :key="index" class="message-bubble" :class="msg.role">
        <div class="message-header">
          <div class="role-icon" :class="msg.role">
            <i v-if="msg.role === 'user'" class="icon-user">👤</i>
            <i v-else class="icon-ai">🤖</i>
          </div>
          <div class="role-title">{{ roleTitles[msg.role] }}</div>
          <div class="message-time">{{ msg.debug.timestamp }}</div>
        </div>
        <div class="message-content">{{ msg.content }}</div>
        <div v-if="msg.debug" class="message-footer">
          <span class="response-time">响应时间：{{ msg.debug.responseTime }}ms</span>
        </div>
      </div>

      <div v-if="isLoading" class="loading-indicator">
        <div class="wave-loader">
          <div class="wave"></div>
          <div class="wave"></div>
          <div class="wave"></div>
        </div>
        <div class="generating-text">思考中...</div>
      </div>
    </div>

    <div class="input-container">
      <div class="input-wrapper">
        <textarea
          v-model="inputText"
          @keydown.enter.exact.prevent="sendMessage"
          placeholder="输入消息，Shift+Enter 换行"
          :disabled="isLoading"
          class="message-input"
        ></textarea>
        <button 
          @click="sendMessage" 
          :disabled="isLoading || !inputText.trim()"
          class="send-button"
        >
          <i class="icon-send">↑</i>
        </button>
      </div>
      <div class="input-footer">
        <button class="debug-toggle" @click="showDebug = !showDebug">
          <i class="icon-debug">⚙️</i>
          {{ showDebug ? '隐藏调试' : '显示调试' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import OpenAI from "openai";

export default {
  data() {
    return {
      inputText: '',
      messages: [],
      isLoading: false,
      error: null,
      lastResponseTime: null,
      statusMessage: '等待输入',
      showDebug: false,
      roleTitles: {
        user: '您',
        assistant: 'AuroraAI助手',
        system: '系统'
      },
      openai: null
    };
  },
  computed: {
    statusClass() {
      return {
        'status-ready': this.statusMessage.includes('就绪'),
        'status-loading': this.isLoading,
        'status-error': this.error
      };
    }
  },
  created() {
    this.initializeOpenAI();
  },
  methods: {
    initializeOpenAI() {
      try {
        this.openai = new OpenAI({
          baseURL: 'https://api.deepseek.com',
          apiKey: 'sk-a739070a51dc4df6a538ff27b132550f',
          dangerouslyAllowBrowser: true
        });
        this.statusMessage = '服务已连接';
      } catch (error) {
        this.handleError('初始化失败', error);
      }
    },
    
    async sendMessage() {
      if (!this.inputText.trim() || this.isLoading) return;
      
      try {
        // 重置状态
        this.error = null;
        this.isLoading = true;
        this.statusMessage = '正在生成回复...';
        
        // 添加用户消息
        this.addMessage('user', this.inputText);
        
        const startTime = Date.now();
        const completion = await this.openai.chat.completions.create({
          messages: [
            { role: "system", content: "You are a helpful assistant." },
            ...this.messages.map(msg => ({
              role: msg.role,
              content: msg.content
            }))
          ],
          model: "deepseek-chat",
        });
        
        const responseTime = Date.now() - startTime;
        this.lastResponseTime = responseTime;
        
        // 添加AI回复
        this.addMessage('assistant', completion.choices[0].message.content, {
          responseTime,
          timestamp: new Date().toLocaleTimeString()
        });
        
        this.statusMessage = `最后回复时间：${new Date().toLocaleTimeString()}`;
        
      } catch (error) {
        this.handleError('API请求失败', error);
        this.addMessage('system', `请求失败：${error.message}`);
      } finally {
        this.inputText = '';
        this.isLoading = false;
        this.$nextTick(() => this.scrollToBottom());
      }
    },
    
    addMessage(role, content, debugInfo = {}) {
      this.messages.push({
        role,
        content,
        debug: {
          timestamp: new Date().toLocaleTimeString(),
          responseTime: debugInfo.responseTime || 0,
          ...debugInfo
        }
      });
      this.scrollToBottom();
    },
    
    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
    
    handleError(context, error) {
      console.error(`${context}:`, error);
      this.error = `${context}: ${error.message}`;
      this.statusMessage = '发生错误';
      setTimeout(() => {
        this.error = null;
      }, 5000);
    }
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  font-family: 'Inter', system-ui, -apple-system, sans-serif;
}

.chat-header {
  background: linear-gradient(135deg, #3B82F6 0%, #6366F1 100%);
  color: white;
  padding: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.logo-gradient {
  font-size: 1.5rem;
  font-weight: 700;
  background: linear-gradient(120deg, #F0F4FF 0%, #FFFFFF 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.beta-badge {
  background: rgba(255, 255, 255, 0.2);
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.1);
}

.status-indicator::before {
  content: '';
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
}

.status-ready { color: #A5F3FC; }
.status-loading { color: #FCD34D; }
.status-error { color: #FCA5A5; }

.messages {
  height: 60vh;
  padding: 1.5rem;
  background: #F8FAFC;
  overflow-y: auto;
}

.message-bubble {
  margin: 1rem 0;
  padding: 1.25rem;
  border-radius: 1rem;
  max-width: 85%;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.message-bubble:hover {
  transform: translateX(5px);
}

.message-bubble.user {
  margin-left: auto;
  background: #3B82F6;
  color: white;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.role-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.role-icon.user {
  background: rgba(255, 255, 255, 0.2);
}

.role-icon.assistant {
  background: #6366F1;
  color: white;
}

.role-title {
  font-weight: 600;
  font-size: 0.875rem;
}

.message-time {
  margin-left: auto;
  font-size: 0.75rem;
  opacity: 0.8;
}

.message-content {
  line-height: 1.6;
  white-space: pre-wrap;
  font-size: 0.95rem;
}

.message-footer {
  margin-top: 1rem;
  font-size: 0.75rem;
  opacity: 0.8;
}

.input-container {
  border-top: 1px solid #E5E7EB;
  padding: 1.5rem;
}

.input-wrapper {
  position: relative;
}

.message-input {
  width: 100%;
  min-height: 120px;
  padding: 1rem 4rem 1rem 1rem;
  border: 1px solid #E5E7EB;
  border-radius: 12px;
  resize: none;
  transition: all 0.2s;
  font-size: 0.95rem;
}

.message-input:focus {
  border-color: #3B82F6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  outline: none;
}

.send-button {
  position: absolute;
  right: 1rem;
  bottom: 1rem;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #3B82F6;
  color: white;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.send-button:hover {
  background: #2563EB;
  transform: translateY(-2px);
}

.send-button:disabled {
  background: #93C5FD;
  cursor: not-allowed;
  transform: none;
}

.wave-loader {
  display: flex;
  justify-content: center;
  gap: 4px;
  height: 20px;
  margin: 2rem 0;
}

.wave {
  width: 4px;
  height: 20px;
  background: #3B82F6;
  animation: wave 1.2s infinite ease-in-out;
  border-radius: 2px;
}

.wave:nth-child(2) { animation-delay: -1.1s; }
.wave:nth-child(3) { animation-delay: -1.0s; }

@keyframes wave {
  0%, 40%, 100% { transform: scaleY(0.4); }
  20% { transform: scaleY(1); }
}

.generating-text {
  text-align: center;
  color: #64748B;
  margin-top: 0.5rem;
  font-size: 0.9rem;
}

.debug-panel {
  background: #F1F5F9;
  padding: 1rem;
  font-size: 0.875rem;
  border-bottom: 1px solid #E5E7EB;
}

.debug-item {
  display: flex;
  gap: 0.5rem;
  padding: 0.5rem 0;
}

.debug-label {
  color: #64748B;
  min-width: 80px;
}

.debug-value {
  color: #1E293B;
  font-weight: 500;
}

.error-message {
  color: #DC2626;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  background: rgba(220, 38, 38, 0.05);
  border-radius: 4px;
}

.debug-toggle {
  background: none;
  border: none;
  color: #64748B;
  cursor: pointer;
  padding: 0.5rem;
  font-size: 0.875rem;
}

.debug-toggle:hover {
  color: #3B82F6;
}

@keyframes dotFlashing {
  0% { opacity: 0.2; transform: scale(0.8); }
  50% { opacity: 1; transform: scale(1); }
  100% { opacity: 0.2; transform: scale(0.8); }
}
</style>